package com.bawei.module_notice.ui


import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.Router
import com.bawei.lib_common.base.state.Empty
import com.bawei.lib_common.base.state.Failed
import com.bawei.lib_common.base.state.Loading

import com.bawei.lib_common.base.state.Success
import com.bawei.module_notice.R
import com.bawei.module_notice.databinding.FragmentNoticeBinding
import com.bawei.module_notice.model.NoticeModel
import com.bawei.module_notice.ui.adapter.NoticeAdapter
import com.bawei.myclub.base.mvvm.view.BaseFragment
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch

@AndroidEntryPoint
@Route(path = Router.Ui.NoticeFragment)
class NoticeFragment : BaseFragment<NoticeViewModel, FragmentNoticeBinding>() {

    override val mLayoutResId: Int = R.layout.fragment_notice
    override val mViewModel: NoticeViewModel by viewModels()

    private val mNoticeAdapter by lazy { NoticeAdapter() }
    private val scrollListener = object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            val layoutManager = recyclerView.layoutManager as LinearLayoutManager
            val lastVisiblePos = layoutManager.findLastVisibleItemPosition()
            val totalItemCount = layoutManager.itemCount
            // 距离底部5项时触发加载更多
            if (lastVisiblePos >= totalItemCount - 5 && dy > 0) {
                mViewModel.loadMore()
            }
        }
    }

    override fun initView() {
        mBinding.rvNotices.apply {
            adapter = mNoticeAdapter
            layoutManager = LinearLayoutManager(requireContext())
            addItemDecoration(DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL))
            addOnScrollListener(scrollListener) // 上拉监听
        }
        // 下拉刷新监听
        mBinding.swipeRefresh.setOnRefreshListener {
            mViewModel.refresh()
        }
    }

    override fun initData() {
        mViewModel.refresh() // 首次进入自动刷新
    }

    override fun initListener() {
        super.initListener()
        lifecycleScope.launch {
            mViewModel.mNoticeState.collect { state ->
                when (state) {
                    is Loading -> {
                        // 下拉刷新时显示SwipeRefresh动画，上拉时显示底部加载
                        if (mViewModel.currentPage == 1) {
                            mBinding.swipeRefresh.isRefreshing = true
                        } else {
                            mNoticeAdapter.setLoadState(NoticeAdapter.LoadState.Loading)
                        }
                    }
                    is Success -> {
                        mBinding.swipeRefresh.isRefreshing = false
                        mNoticeAdapter.setLoadState(NoticeAdapter.LoadState.NotLoading)
                        mNoticeAdapter.submitList(mViewModel.notices)
                    }
                    is Failed -> {
                        mBinding.swipeRefresh.isRefreshing = false
                        mNoticeAdapter.setLoadState(NoticeAdapter.LoadState.NotLoading)
                    }

                    Empty ->{

                    }
                }
            }
        }
        addCommonStateListener(mViewModel.mNoticeState) // 复用基类状态监听（空布局、错误等）
        // 列表项点击 → 跳转到公告详情页
        mNoticeAdapter.onItemClickListener = object : NoticeAdapter.OnItemClickListener {
            override fun onItemClick(notice: NoticeModel) {
                // 1. 传递公告 ID 到详情页（根据实际路由方案调整）
                ARouter.getInstance()
                    .build(Router.Ui.NoticeDetailActivity) // 详情页路由路径（需提前定义）
                    .withInt("noticeId", notice.id)   // 传递公告 ID
                    .navigation()
            }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding.rvNotices.removeOnScrollListener(scrollListener) // 移除监听避免内存泄漏
    }
}